﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EasyGrocer.DataLayer;
using EasyGrocer.BusinessLayer.ServiceRepository;
namespace EasyGrocer.UI
{
    public partial class Categories : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataList1.ItemCommand += new DataListCommandEventHandler(DataList1_ItemCommand);
            if(!Page.IsPostBack)
            {
                ICategoryServiceRep cRep = BusinessServiceFactory.CreateCategoryService();
                IEnumerable<Category> rootCategory = cRep.GetRootChildren();
                //IEnumerable<Category> categories1 = dc.Categories.Where(a => a.CategoryRelations1 == null);
                DataList1.DataSource = rootCategory;
                DataList1.DataBind();
            }
        }

        private void DataList1_ItemCommand(object sender, EventArgs e)
        {
            CommandEventArgs args = (CommandEventArgs)e;
            Guid categoryId = new Guid(((CommandEventArgs)e).CommandArgument.ToString());
            EasyGrocerDBDataContext dc = new EasyGrocerDBDataContext();
            ICategoryServiceRep cRep = BusinessServiceFactory.CreateCategoryService();
            IEnumerable<Category> childrenC = cRep.GetChildrenById(categoryId);
            //get children categories
            if (childrenC.Count() > 0)
            {
                DataList1.DataSource = childrenC;
                DataList1.DataBind();
            }
            else
            {
                Response.Redirect("ProductList.aspx"+"?id="+categoryId);
            }
        }
    }
}
